<template>
  <div>
    <Category :isDisabled="!isTable"></Category>
    <el-card class="box-card attrCard">
      <div v-show="isTable">
        <el-button
          icon="Plus"
          type="primary"
          @click="handlerUpdateAttr()"
          :disabled="!categoryStore.chooseCategory[2]"
          >添加平台属性</el-button
        >
        <el-table
          v-loading="tableLoading"
          :data="categoryData"
          :border="true"
          style="margin: 10px 0px"
        >
          <el-table-column
            type="index"
            align="center"
            width="80"
            label="序号"
          ></el-table-column>
          <el-table-column label="属性名称" width="120">
            <template #="{ row }">
              {{ row.attrName }}
            </template>
          </el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <el-tag
                style="margin: 5px"
                v-for="(i, index) in row.attrValueList"
                :key="index"
                type="success"
                >{{ i.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #="{ row }">
              <el-button
                type="warning"
                size="small"
                icon="Edit"
                @click="handlerUpdateAttr(row)"
                >修改</el-button
              >
              <el-popconfirm
                width="220"
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="InfoFilled"
                icon-color="#626AEF"
                :title="`你确定要删除【${row.attrName}】吗?`"
                @confirm="handlerDeleteAttr(row.id)"
              >
                <template #reference>
                  <el-button>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="!isTable">
        <el-form inline>
          <el-form-item label="属性名称">
            <el-input
              placeholder="请输入属性名字"
              v-model="updateAttrObj.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          icon="Plus"
          type="primary"
          @click="addValueName"
          :disabled="!updateAttrObj.attrName"
          >添加属性值</el-button
        >
        <el-button type="default" @click="cancelAddAttr">取消</el-button>

        <el-table
          :data="updateAttrObj.attrValueList"
          :border="true"
          style="margin: 10px 0px"
        >
          <el-table-column
            type="index"
            align="center"
            width="80"
            label="序号"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input
                :ref="(element: any) => (inputRefArr[$index] = element)"
                @blur="changeEditMode($index, false)"
                v-if="row.allowEdit"
                v-model="row.valueName"
              ></el-input>
              <div @click="changeEditMode($index, true)" v-else>
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #="{ $index }">
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="deleteValueName($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button
          type="primary"
          @click="submitUpdateAttr"
          :disabled="!updateAttrObj.attrName"
          >保存</el-button
        >
        <el-button type="default" @click="cancelAddAttr">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import useCategoryStore from "@/store/modules/category";
import type { AttrResponseData, AttrObj } from "@/api/product/attr/type";
import * as attrRequest from "@/api/product/attr";
import { nextTick, onBeforeUnmount, reactive, ref, watch } from "vue";
import { ElNotification } from "element-plus";
let categoryStore = useCategoryStore();
let categoryData = ref<AttrObj[] | []>([]);
let tableLoading = ref(false);
let isTable = ref(true);
let updateAttrObj = reactive<AttrObj>({
  attrName: "",
  attrValueList: [],
  categoryId: 0,
  categoryLevel: 3,
});

//存储el-input的ref用于编辑属性值时自动获取焦点
//通过组件上 :ref="(vc:any)=>inputRefArr[$index]=vc"进行添加的
let inputRefArr = ref<any>([]);

// 封装获取当前已选分类下的数据方法
const getAttrList = async () => {
  let result: AttrResponseData = await attrRequest.reqattrInfoList(
    categoryStore.chooseCategory[0],
    categoryStore.chooseCategory[1],
    categoryStore.chooseCategory[2],
  );
  if (result.code == 200) {
    categoryData.value = result.data;
  }
};

watch(
  () => categoryStore.chooseCategory[2],
  async (newVal) => {
    try {
      categoryData.value = [];
      if (!newVal) return;
      tableLoading.value = true;
      getAttrList();
      tableLoading.value = false;
    } catch (error) {
      tableLoading.value = false;
    }
  },
  { immediate: true },
);

//当点击添加属性或修改按钮
// aid：选填，表示要修改的属性id
// attrName：选填，表示要修改的属性名称
const handlerUpdateAttr = async (row?: AttrObj) => {
  //每次点击先清空数据,该方法的意思是参数二覆盖合并参数一
  Object.assign(updateAttrObj, {
    attrName: "",
    attrValueList: [],
    categoryId: categoryStore.chooseCategory[2],
    categoryLevel: 3,
  });
  delete updateAttrObj.id;
  isTable.value = false;
  // 如果接受到row表示是修改，则将要修改的数据合并到表单数据中完成回显
  if (row) {
    // 用perse和stringify是因为打乱assign方法的浅拷贝问题
    // 即操作会同时影响两个对象，导致修改同时也会影响原数据，通过此深拷贝可解决
    Object.assign(updateAttrObj, JSON.parse(JSON.stringify(row)));
  }
};

// 当点击取消按钮
const cancelAddAttr = () => {
  isTable.value = true;
};

//当点击添加属性值
const addValueName = () => {
  updateAttrObj.attrValueList.push({ valueName: "", allowEdit: true });
  nextTick(() => {
    inputRefArr.value[inputRefArr.value.length - 1].focus();
  });
};
//当点击删除属性值
const deleteValueName = (index: number) => {
  updateAttrObj.attrValueList.splice(index, 1);
};

//当提交表单更新属性
const submitUpdateAttr = async () => {
  let result = await attrRequest.reqsaveAttrInfo(updateAttrObj);
  if (result.code == 200) {
    isTable.value = true;
    getAttrList();
  } else {
    console.log(result.message);
  }
};

//当删除属性被点击
const handlerDeleteAttr = async (id: number) => {
  let result = await attrRequest.reqdeleteAttr(id);
  if (result.code == 200) {
    getAttrList();
  }
};

//控制编辑模式还是查看模式
const changeEditMode = (index: number, isEdit: boolean) => {
  //如果从编辑模式变成查看模式，必须检查是否有值
  if (!isEdit) {
    if (updateAttrObj.attrValueList[index].valueName) {
      // 非法情况二：属性值重复
      let i = 0;
      let repeat = false;
      updateAttrObj.attrValueList.forEach((item) => {
        if (item.valueName == updateAttrObj.attrValueList[index].valueName) {
          i++;
        }
        if (i > 1) {
          repeat = true;
          return;
        }
      });
      if (!repeat) {
        //进入查看模式，且自动获取焦点
        updateAttrObj.attrValueList[index].allowEdit = isEdit;
      } else {
        //重复，删除该项
        updateAttrObj.attrValueList.splice(index, 1);
        ElNotification({
          type: "error",
          message: "属性值请勿重复",
          title: `请注意`,
        });
      }
    } else {
      //非法情况一：如果属性值为空，删除该项
      updateAttrObj.attrValueList.splice(index, 1);
      ElNotification({
        type: "error",
        message: "属性值不能为空,已自动清除该属性，如要撤销，请返回上一页",
        title: `请注意`,
      });
    }
  } else {
    updateAttrObj.attrValueList[index].allowEdit = isEdit;
    nextTick(() => {
      inputRefArr.value[index].focus();
    });
  }
};

//当组件销毁，页面切换的时候，清空仓库数据（此步根据实际情况而定，也可不清空）
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style scoped lang="scss">
.attrCard {
  margin-top: 10px;
}
</style>
